'use strict';
const Service = require('egg').Service;
const { Op, fn, col } = require('sequelize');

class CustomerService extends Service {
  /* -----------------增----------------- */
  /**
   * 增加新客户
   * @param {any} body 传入的新用户信息
   *  */
  async addCustomer(body) {
    const { ctx } = this;
    const created = await ctx.model.Customer.Customer.create({
      ...body,
    });
    if (created) {
      return created;
    }
    return ctx.throw('用户已存在');
  }
  /* 添加联系人 */
  async addContact(body) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      const [contact, created] = await ctx.model.Customer.Contact.findOrCreate({
        where: {
          name: body.name,
        },
        default: body,
      });
      await ctx.model.Customer.ContactCustomer.create({
        customer: body.customerId,
        contact: contact.id,
      });
      transaction.commit();
      return contact;
    } catch (error) {
      console.log(error);
      transaction.rollback();
      ctx.throw('添加失败');
    }
  }

  // 新增客户追踪记录
  async addTrack({ info, type, customer_id, staff_id }) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      const code = (
        await ctx.model.Customer.Trackrecord.create({
          info,
          type,
          customer_id,
        })
      ).get({ plain: true });
      await ctx.model.Customer.CodeStaff.create({
        code_id: code.id,
        staff_id,
      });
      transaction.commit();
      return code;
    } catch (error) {
      console.log(error);
      transaction.rollback();
      ctx.throw('添加失败');
    }
  }

  // 发起用户申请
  async addExamine(body) {
    const { ctx } = this;
    try {
      if (body.customer_id && body.staff_id && body.type) {
        const application = await ctx.model.Customer.Examine.create({
          ...body,
        });
        return application;
      }
    } catch (error) {
      ctx.throw('添加失败');
    }
  }
  /* -----------------查----------------- */
  /**
   * 查询用户是否撞单
   * @param {Object} body 查询的信息
   */
  async findCustomerByName(body) {
    const { ctx } = this;
    const customer = await ctx.model.Customer.Customer.findOne({
      where: { ...body },
      attributes: ['id', 'name'],
    });
    if (customer) {
      return customer.get({ plain: true });
    }
    return;
  }

  /* 查询潜在客户列表 */
  async findLatentCustomer(body) {
    const { ctx } = this;
    const { name, email, phone, ...info } = body;
    const customers = await ctx.model.Customer.Customer.findAll({
      where: {
        name: {
          [Op.like]: '%' + name + '%',
        },
        email: {
          [Op.like]: '%' + email + '%',
        },
        phone: {
          [Op.like]: '%' + phone + '%',
        },
        ...info,
        state: 0,
      },
      include: [
        {
          model: ctx.model.Customer.Contact,
          as: 'Contacts',
          through: { attributes: [] },
        },
      ],
    });
    if (customers.length > 0) {
      return customers;
    }
    return null;
  }

  // 模糊查询用户
  async fuzzyToCustomer({ name }) {
    const { ctx } = this;
    try {
      const List = await ctx.model.Customer.Customer.findAll({
        where: {
          name: {
            [Op.like]: '%' + name + '%',
          },
        },
        attributes: ['id'],
        raw: true,
      });
      return List;
    } catch (error) {
      ctx.throw('查询失败');
    }
  }
  /* -----------------改----------------- */
  /* 修改用户 */
  async editCustomer({ id, ...info }) {
    const { ctx } = this;
    try {
      const customer = await ctx.model.Customer.Customer.update(
        {
          ...info,
        },
        {
          where: {
            id,
          },
        }
      );
      if (customer.length > 0) {
        return '修改用户成功';
      }
    } catch (error) {
      return ctx.throw('修改用户失败');
    }
  }
  /* 修改联系人信息 */
  async editContact({ id, ...info }) {
    const { ctx } = this;
    try {
      const contact = await ctx.model.Customer.Contact.update(
        {
          ...info,
        },
        {
          where: {
            id,
          },
        }
      );
      if (contact[0] > 0) {
        return '修改用户成功';
      }
    } catch (error) {
      return ctx.throw('修改用户失败');
    }
  }
  /* 转移客户 */
  async transferCustomer({ from, to }) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Customer.Customer.update(
        {
          staff: to,
        },
        {
          where: {
            staff: from,
          },
        }
      );
      if (result[0] > 0) {
        return '转移客户成功';
      }
      return '转移客户失败';
    } catch (error) {
      console.log(error);
      return ctx.throw('转移客户失败');
    }
  }
  /* -----------------删----------------- */
  /* 删除联系人 */
  async deleteContact({ id }) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      const customerRes = await ctx.model.Customer.ContactCustomer.destroy({
        where: {
          contact: id,
        },
      });
      const contactRes = await ctx.model.Customer.Contact.destroy({
        where: {
          id,
        },
      });
      if (contactRes && customerRes) {
        transaction.commit();
        return '删除联系人成功';
      }
    } catch (error) {
      console.log(error);
      transaction.rollback();
      ctx.throw('删除联系人失败');
    }
  }
  /* 删除追踪记录 */
  async deleteTrack({ id }) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      await ctx.model.Customer.CodeStaff.destroy({
        where: {
          code_id: id,
        },
      });
      await ctx.model.Customer.Trackrecord.destroy({
        where: {
          id,
        },
      });
      transaction.commit();
      return '删除成功';
    } catch (error) {
      transaction.rollback();
      ctx.throw('删除失败');
    }
  }
}

module.exports = CustomerService;
